package com.jay.android.view;

import java.util.Calendar;

import android.content.Context;
import android.os.Handler;
import android.os.SystemClock;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.widget.TextView;

public class DigitalClock extends TextView {
	private Calendar mCalendar;
	private String mFormat1 = "hh : mm";
	private String mFormat2 = "hh   mm";

	private Runnable mTicker;
	private Handler mHandler;

	private boolean mTickerStopped = false;

	public DigitalClock(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		initClock(context);
	}

	public DigitalClock(Context context, AttributeSet arrts) {
		// TODO Auto-generated constructor stub
		super(context, arrts);
		initClock(context);
	}

	private void initClock(Context context) {
		if (mCalendar == null) {
			mCalendar = Calendar.getInstance();
		}
	}

	@Override
	protected void onAttachedToWindow() {
		// TODO Auto-generated method stub
		super.onAttachedToWindow();

		mTickerStopped = false;
		mHandler = new Handler();

		mTicker = new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (mTickerStopped)
					return;
				mCalendar.setTimeInMillis(System.currentTimeMillis());
				if(SystemClock.uptimeMillis() / 1000 % 2 == 0)
					setText(DateFormat.format(mFormat1, mCalendar));
				else 
					setText(DateFormat.format(mFormat2, mCalendar));
				invalidate();
				long now = SystemClock.uptimeMillis();
				long next = now + (1000 - System.currentTimeMillis() % 1000);

				mHandler.postAtTime(mTicker, next);
			}
		};

		mTicker.run();
	}

	@Override
	protected void onDetachedFromWindow() {
		// TODO Auto-generated method stub
		super.onDetachedFromWindow();
		mTickerStopped = true;
	}

}
